<?php

	include_once("cmsConfig.php");// this should have already been included..	
	include_once("lib/CmsWriter.php");

	$documentCode = extractNumberWithKeyFromArray('documentCode', $_REQUEST);
	$formId = 123;//extractNumberWithKeyFromArray('formId', $_REQUEST);//always 123 for postings
	$addPosting = extractStringWithKeyFromArray('addPosting', $_REQUEST);
	$notifyGroupOfPosting = extractBooleanWithKeyFromArray('notifyGroupOfPosting',$_REQUEST, false);
	
	$addPosting = $addPosting === "YES";
	$result = null;
	
	
	$formDescriptionTableWriter = new CmsTableWriter("formdescriptor", $db);
	$formDescription = $formDescriptionTableWriter->readItem( $formId );
	if (!($formDescription)) die("Where did the form descriptor go???" );
		
	$document = null;
	if (!is_null($documentCode)) {
		$document  = $cmsDocument->openDocument($documentCode);
	}
	
	$topic = null;	
	if (!$document) 
		$document = null;
	else 
		$topic = $document->categorycode;
		

	if (is_null($document)) {
		//try and get the topic out of the incoming request.
		$topic = extractNumberWithKeyFromArray('topic', $_REQUEST);
	}
	
	if (is_null($topic) && isset($_REQUEST['categorycode']) && !is_null($_REQUEST['categorycode'])) {
		$topic = $_REQUEST['categorycode'];
	}
	
	//extract the gid0r
	//$gid = 
	$topicTitle = "Back to Topics";
	$topicDocument = null;
	if (!is_null($topic) ){
		$topicDocument = $cmsDocument->openDocument($topic);
		$topicTitle = $topicDocument->title;
	}
	
	//we need to get the posting topics out etc.. 
//	$topic = ;//we will always take the parents if we have a parent.. .
	if ($addPosting){
		
		//check if we are adding a posting or a comment.
		// map fields as needed.. 
		
		if (is_null($documentCode)){
			//no document code so we are adding a new document.... dont need to set extras as we have all of what we need.
			//every thing required needs to be passed in..
			//$_REQUEST['']//
			$_REQUEST['value'] = null;//$document->documentcode;
			if (!is_null($topicDocument)) {
				$_REQUEST['gid'] = $topicDocument->gid;
			}
		} else if (!is_null($document)){
			//we need to add
			// 1. a title.. RE: existing title
			if (isset($document->title)) {
				$_REQUEST['title'] = "RE: ". $document->title;
			}
			if (isset($document->documentcode)) {
				//set the parent
				$_REQUEST['value'] = $document->documentcode;
			}
			$_REQUEST['gid'] = $document->gid;//take the permissions from the parent.
		} else {
			//we may need to throw errors here...
		}

		// extract the topic..
		//$_REQUEST['categorycode'] =  is_set($_REQUEST['topic']) ? null : $_REQUEST['topic'];
		
		//things that get set regardless
		// 1. the topic..// we need to mangle the request directly..
		//$_REQUEST['categorycode'] = $topic;
		$_REQUEST['active'] = 1;
		
		
		//get a cmsWriter and save things.. we dont need a document code as we are not editing.
		$cmsWriter = new CmsWriter($formId, null, $_REQUEST, $authInfo, $db );
		$result = $cmsWriter->processFormData();
		
		// figure out if anything went wrong.
		if ($result->hasErrors) {
			// we need to decide how to handle the errors
		} else {
			//our thing was dealt with and saved.. so we can carry on..
			//we need to set the topic and document code here..
			// and clear out the posted in variables..
			if (is_null($documentCode)) {
				$documentCode = $cmsWriter->documentCode;
			}
			unset($_REQUEST['content'] );
			unset($_REQUEST['title'] );
			$topic = $_REQUEST['categorycode'];//set this back for use later..
			$content=null;
			$title = null;		
						
			if (CMS_POSTINGS_EMAIL_NOTIFY && $notifyGroupOfPosting){
			//spam o matic..
			//get the users in the group of the document.
				$uids  = usersForGroup( $_REQUEST['gid'], $db);
				if (is_array($uids) && count($uids) > 0 ) {
					$toAddresses = array();
					$q = "SELECT email,firstname, lastname FROM user WHERE uid IN (" . implode(",", $uids) . ")";
					$db->executeQuery($q);
					while($user = $db->nextObject()) {
						if (!is_null($user->email) && 
						preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $user->email))
							array_push($toAddresses, $user->email);
					}
					if (count($toAddresses) > 0) {
						//$to, $from, $cc, $bcc, $subject, $body, $param, $force
						$home = CMS_HTTP_HOST . CMS_HOME;
						$siteTitle = TITLE;
						$emailBody  = <<< EOD
--------------------------------------------------------
                     NEW POSTING
--------------------------------------------------------
	
A new posting or comment has been added to the $siteTitle
Intranet, into the following discussion forum:

	"$topicTitle". 

To view the message board, click the link below and log in to the
$siteTitle Intranet.
	
$home?fileNo=100&documentCode=$documentCode&topic=$topic
						
--------------------------------------------------------
This was an automated email sent to you by the from the 
$siteTitle Intranet. Please do not reply to this email. 
--------------------------------------------------------
EOD;
						simpleEmailer(
							array(),
							CMS_EMAIL_FROM,
							array(),
							$toAddresses,
							"New Posting",
							$emailBody,
							array()
						);
						
					}
				}
			}
		}
	}

?>
<div id="cms_postings_container" >
<H1 class="cms_heading">Message Board Forums > <?= $topicTitle ?></H1>
<div id="cms_browse_topdivider" class="cms_browse_divider"></div>
<?
	// go and display the posting tree..
	displayPosting( $documentCode, $cmsDocument);

	//simple little lable hack.
	$postingType = "Comment";
	if (is_null($documentCode)) {
		$postingType = "Posting";
	}
	
	//pull out things from the post if we need to display them. we will clear these out.. further up
	//if they are saved successfully.		
	$content = extractStringWithKeyFromArray('content', $_REQUEST);
	$title = extractStringWithKeyFromArray('title', $_REQUEST);
	
	if (addFormAuth( $authInfo, $formDescription ,null, $db))  {
	
?>
<form enctype="multipart/form-data" id="cms_add_posting_form" name="cms_add_posting_form" class="cms_add_posting_form" action="<?= CMS_HOME . "?fileNo=" . $fileNo ?>" method="POST">
<input type="hidden" name="addPosting" value="YES" />
<div class="cms_add_posting_container">
	<div class="cms_add_posting_header"><span style="font-size: 14px; font-weight: bold;">Add <?= $postingType ?></span>
(Enter your <?= $postingType ?> in box below and click update)</div>
<?
	// if we have no document code.. then we are .. adding a new posting..
	// and we need to be able to enter a title..

	if (is_null($documentCode)) {
?>
<div id="cms_add_posting_title">
<div id="cms_add_posting_title_label">Title</div>
<div id="cms_add_posting_title_input">
	<input type="text" name="title" id="" value="<?= str_replace('"','&quot;', $title) ?>" />
</div>
<div style="clear:both;" ></div>
<?
validationMessageForFieldWithLabel($result, 'title','Subject');
?>
</div>
<?
	} else {
?>
<input type="hidden" name="documentCode" value="<?= $documentCode ?>" />
<?
	}
	if (is_null($topic)) {	
?><br/>
<div>
<div><b>Topic</b></div>
<div>
</div>
<?
validationMessageForFieldWithLabel($result, 'categorycode','Topic');
?>
</div>
<?
	} else {
?>		
<input type="hidden" name="categorycode" value="<?= $topic ?>" />		
<?		
	}
?>



<div id="cms_add_posting_editor">
<?
	$contentBlockContentId="";
print <<< EOD
	      <script language="javascript" type="text/javascript">
	      tinyMCE.init({
			      mode : "exact",
			      elements : "content",
			      theme : "advanced",
			      plugins : "table,advhr,iespell,insertdatetime,searchreplace,contextmenu,paste,advlink",
			      theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,hr,separator,formatselect,separator,link,unlink,separator,cut,copy,pastetext,iespell,separator,undo,redo,separator,code",
			      theme_advanced_buttons2: "",
			      theme_advanced_buttons3 : "",
			      theme_advanced_blockformats : "h1,h2,h3,h4",
			      theme_advanced_toolbar_location : "top",
			      theme_advanced_styles: "",
			      theme_advanced_toolbar_align : "left",
			      theme_advanced_path_location : "bottom",
			      plugin_insertdate_dateFormat : "%Y-%m-%d",
			      plugin_insertdate_timeFormat : "%H:%M:%S",
			      extended_valid_elements : "hr[class|width|size|noshade],span[class|align|style],div[class|align|style]",
			      file_browser_callback : "mcFileManager.filebrowserCallBack",
			      theme_advanced_resize_horizontal : false,
			      theme_advanced_resizing : false
	      });
	      </script>
		<textarea id="content" name="content" class="cms_postings_edit">$content</textarea>
EOD;
?>
</div>
<?
	if (CMS_POSTINGS_EMAIL_NOTIFY  ) {
?>
<div id="cms_add_posting_notify">
Notify group of new postings? <input type="checkbox" value="1" name="notifyGroupOfPosting" checked="checked" />
</div>
<?
	}
?>
<div id="cms_add_posting_attachment">
		<div id="cms_add_posting_attachment_label">
		Attachment
		</div>
		<div id="cms_add_posting_attachment_input">
			<input type="file" name="shortdescription" id="cms_add_posting_file" />
		</div>
		<div style="clear:both;" ></div>
	</div>
	<div id="cms_add_posting_submit">
		<a href="javascript:document.forms['cms_add_posting_form'].submit();" ><img src="/cms/images/button_go.gif" /></a>
	</div>
</div>
</form>
<?

	}
	
$upUrl = $_SERVER['PHP_SELF'] . "?fileNo=1&formid=123&topic=" . $topic;

?>
<table style="clear: both;" cellpadding="0" cellspacing="0" width="100%" border="0">
	<TR> 
	  <TD align="left" colSpan="3"><IMG height="7" src="/cms/images/greyline.gif" width="660" /></TD>
	</TR>
	<TR> 
	  <TD class="cms_browsetext" width="35"><a href="<?= $upUrl ?>"><img src="/cms/html/files/images/icon_folderup.gif" width="35" height="20" /></a></TD>
	  <TD class="cms_browsetext" "><a href="<?= $upUrl ?>"><i>.. View all Discussions.<i></a></TD>
	  <TD width="1"><IMG height="20" src="/cms/images/spacer.gif" width="1" /></TD>	
	<TR> 
	  <TD align="left" colSpan="3"><IMG height="7" src="/cms/images/greyline.gif" width="660" /></TD>
	</TR>  
</table>
<?
	function displayPosting( $documentCode, &$cmsDocument ) {//ick.. should really consturct my own cmsdocument.. 
		// read the posting..
		$posting = null;
		if (!is_null($documentCode))
			$posting = $cmsDocument->openDocument( $documentCode );
	
		if (!is_null($posting)) {	
			$commentText = magicClean($posting->content);
			$commentDate = magicClean($posting->datelogged);
			$commentTitle = magicClean($posting->title);
			// get the user that posted it..
			$poster = null;
			$cmsDocument->db->executeQuery("SELECT * FROM user WHERE uid=" . $posting->uid);
			if (!($poster = $cmsDocument->db->nextObject())) {
				$poster = new stdClass();
				$poster->firstname = "";
				$poster->lastname= "unknown";
			} 
			print <<< EOD
<TABLE width="100%" border="0" cellpadding="0" cellspacing="0" class="cms_postings_parent">
<TR>            
	<TD>
    	<img class="cms_postings_child_comment_icon" width="35" height="20" src="/cms/html/postings/images/icon_comment.gif"  > 
    	<b>$commentTitle</b> by: <b>$poster->firstname $poster->lastname</b><br/>
    	<i>$commentDate</i><br />
	</TD>
</TR>
<TR> 
	<TD class="cms_postings_parent_text">
		$commentText
	</TD>
</TR>
EOD;

			//get the file data... murp..			
			if ( $posting->shortdescription ) {
				echo "<TR><TD >";
				//lookup file details..
				$attachmentDetails = getPostingAttachmentDetails($posting, $cmsDocument->db);
				$attachmentUrl = getPostingAttachmentUrl($posting);				
				//
				if (! is_null($attachmentDetails)){
					print <<< EOD
              <img  class="cms_postings_parent_attachment_icon" src="/cms/html/postings/images/icon_comment_file.gif" width="35" height="35" >Related 
                File: <A target="_blank" href="$attachmentUrl"><b>$attachmentDetails->filename</b></A>
EOD;
				} else {
					echo "THERE APPEARS TO BE SOME SORT OF A MUCKUP... <br />The document says I should have an attachment, but i cant find it.";
				}
				echo "</TD></TR>";
			}
			print <<< EOD
</TABLE>	
EOD;

		//get children...
		$cmsDocument->flush();//need to clear it out for reuse
		$cmsDocument->addDocumentType('docPosting');
		$cmsDocument->addConstraint('value',$posting->documentcode,'=');//key value type
		$cmsDocument->addConstraint('active', 1, '=' );
		
		$cmsDocument->resetIterator();
		//- - -
			while($childPosting = $cmsDocument->nextDocument()){
				
				$childPostingText = magicClean($childPosting->content);
				$childPostingDate = magicClean($childPosting->datelogged);

				$poster = null;
				$cmsDocument->db->executeQuery("SELECT * FROM user WHERE uid=" . $childPosting->uid);
				if (!($poster = $cmsDocument->db->nextObject())) {
					$poster = new stdClass();
					$poster->firstname = "";
					$poster->lastname= "unknown";
				} 
							
				print <<< EOD
<TABLE width="100%" border="0" cellpadding="0" cellspacing="0" class="cms_postings_child">
	<TR>                
		<TD>
			<img class="cms_postings_child_comment_icon" width="35" height="20" src="/cms/html/postings/images/icon_comment.gif" />Reply 
			by: <b>$poster->firstname $poster->lastname</b><br />
			<i>$childPostingDate</i>
		</TD>
	</TR>
<TR> 
	<TD class="cms_postings_child_text">
$childPostingText
	</TD>
</TR>
EOD;
	
				if ($childPosting->shortdescription) {

					echo "<TR><TD>";
					$attachmentDetails = getPostingAttachmentDetails($childPosting, $cmsDocument->db);
					$attachmentUrl = getPostingAttachmentUrl($childPosting);
					if(!is_null($attachmentDetails)){		
						print <<< EOD
	              <img class="cms_postings_child_attachment_icon" src="/cms/html/postings/images/icon_comment_file.gif" width="35" height="35">Related 
	                File: <A target="_blank"  href="$attachmentUrl"><b>$attachmentDetails->filename</b></A>
EOD;
					} else {
					echo "THERE APPEARS TO BE SOME SORT OF A MUCKUP... <br />The document says I should have an attachment, but i cant find it.";						
					}
					
					echo "</TD></TR>";
				}
				
				print <<< EOD
	              </TABLE>
EOD;
			}
		}
	}

	function validationMessageForFieldWithLabel($message, $element, $label){
		if (!is_null($message) && $err=$message->getMessageForKey($element) ) {
			print( '<br/><span class="cms_error">' . $label .' '. $err .'</span>');//
		} 				
	}
	
	function getPostingAttachmentDetails(&$post, &$db){
		$attachmentDetails=null;
		$db->executeQuery("SELECT  filename, filesize, mimetype FROM binarydata WHERE id=" . $post->shortdescription ." AND filetypecode=1 AND documentcode=". $post->documentcode . "");//there should be an element type here, but it is not majorly important as there is only one blob per record
		if (!($attachmentDetails = $db->nextObject())) {
			//add some bollocks here.. really, if we get nothing.. not sure about this really,
			// in all honesty.. if we get noting back here
			// the data is really fucked up..
			/// so we could do this
			//$attachmentDetails = new stdClass();
			//$attachmentDetails->filename = "file";
			//$attachmentDetails->filesize = "unknown";
			//$attachmentDetails->mimetype = "application/octet-stream";
			// but for now we will return lord nullness...
			return null;
		}
		return $attachmentDetails;		
	}
	
	function getPostingAttachmentUrl($post){
		return "/html/blob.php?attach=true&documentCode=" . $post->documentcode . "&foo=" . md5( "slartybartfast" .(microtimeFloat() % microtimeFloat()) );
	}
?>
</div>
